package ace.module.upms.core.impl.dao.aggregate.impl;

import ace.cmp.core.constants.CoreConstant;
import ace.module.upms.core.impl.dao.aggregate.UpmsOrganizationAggregate;
import ace.module.upms.core.impl.dao.entity.QUpmsOrganization;
import ace.module.upms.core.impl.dao.entity.QUpmsOrganizationAccount;
import ace.module.upms.core.impl.dao.entity.UpmsOrganization;
import ace.module.upms.core.impl.dao.repository.UpmsOrganizationRepository;
import com.querydsl.core.types.ExpressionUtils;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 组织 aggregate implement.
 *
 * @author Caspar
 */
@Slf4j
@AllArgsConstructor
@Component
public class UpmsOrganizationAggregateImpl implements UpmsOrganizationAggregate {

  private final UpmsOrganizationRepository upmsOrganizationRepository;

  @Override
  public List<UpmsOrganization> getByUpmsApIdAndIamAccountId(Long upmsAppId, Long iamAccountId) {
    return this.upmsOrganizationRepository.queryMany(sqlQuery -> {
      QUpmsOrganization qUpmsOrganization = new QUpmsOrganization("org");
      QUpmsOrganizationAccount qUpmsOrganizationAccount = new QUpmsOrganizationAccount("org_account");
      return sqlQuery
          .distinct()
          .select(qUpmsOrganization)
          .from(qUpmsOrganization)
          .innerJoin(qUpmsOrganizationAccount)
          .on(qUpmsOrganization.id.eq(qUpmsOrganizationAccount.upmsOrgId))
          .where(ExpressionUtils.allOf(
              qUpmsOrganization.upmsAppId.eq(upmsAppId),
              qUpmsOrganization.deleteFlag.eq(CoreConstant.DELETE_FLAG_NOT),
              qUpmsOrganizationAccount.upmsAppId.eq(upmsAppId),
              qUpmsOrganizationAccount.iamAccountId.eq(iamAccountId),
              qUpmsOrganizationAccount.deleteFlag.eq(CoreConstant.DELETE_FLAG_NOT)
          ));
    });
  }
}